
package com.su.dev.sipder;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.su.dev.main.TextUtils;

public class URLMatcher {
    // 编码
    private static final String ECODING = "UTF-8";
    // 获取img标签正则
    //private static final String IMGURL_REG = "<img.*src=(.*?)[^>]*?>";
    private static final String IMGURL_REG = "<img.*src=\"(.*?)\"\\s*>";
    // 获取src路径的正则
    private static final String IMGSRC_REG = "(https|http)://[^\\s]*(jpg|png|jpeg|bmp|gif){1}";

    public String getHtml(String urlString) {
        try {
            URL url = new URL(urlString);
            URLConnection connection = url.openConnection();
            InputStream inputStream = connection.getInputStream();
            byte[] buffer = new byte[1024];
            StringBuilder builder = new StringBuilder();
            int count = 0;
            while ((count = inputStream.read(buffer)) > 0) {
                builder.append(new String(buffer, 0, count));
            }
            inputStream.close();
            return builder.toString();

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "";
    }

    /***
     * 获取ImageUrl地址
     * 
     * @param HTML
     * @return
     */
    public List<String> getImageUrl(String HTML) {
        Matcher matcher = Pattern.compile(IMGURL_REG).matcher(HTML);
        List<String> listImgUrl = new ArrayList<String>();
        while (matcher.find()) {
            listImgUrl.add(matcher.group(0));
        }
        return listImgUrl;
    }
   final static Pattern SRC_PATTERN;
    static{
        SRC_PATTERN = Pattern.compile(IMGSRC_REG,Pattern.CASE_INSENSITIVE);
    }
    public String getRealImgSrc(String urlWithHtml) {
        if (!TextUtils.isEmpty(urlWithHtml)) {
            System.out.println(urlWithHtml);
            Matcher matcher = SRC_PATTERN.matcher(urlWithHtml);
            if (matcher.find()) {
                System.out.println("pass");
                return matcher.group(0);
            }

        }
        System.out.println("pass2");
        return "";

    }

}
